const {
  http
} = require("../../../../utils/apiutils")

Page({
  /**
   * 页面的初始数据
   */
  data: {
    checked: true,
    show1: false,
    sIndex: 0,
    sh: "300",
    dataList: [],
    checked1: false,
    checked2: false,
    titlist: [{
      name: "已报名",
      value: 1,
    }, {
      name: "工作中",
      value: 2,
    }, {
      name: "结算中",
      value: 3,
    }],
    tabActive: 1,
    pageNo: 1,
    pageSize: 10,
    loading: false, // true正在请求
    hasMore: true, // true 有更多
    btnText: '',
    funcStatus: 0, // 1 不录用 2 录用  19 不结算 9 结算
    isPl: false,  // true  不批量  false批量
    checkId: '',
    count: {
      sx: 0,
      yl: 0,
      sum: 0
    },
    count1: {
      sx: 0,
      yl: 0,
      sum: 0
    },
    tabArr: [
      {
        titme: '已报名',
        num: 0,
        name: "1"
      },
      {
        titme: '结算',
        num: 0,
        name: "4"
      }
    ],
    toast: false,
    workTime: '',
    uId: '',
    copyworkinfo: {}
  },
  onclickAdd: function () {
    if (this.data.sIndex < this.data.titlist.length - 1) {
      this.setData({
        sIndex: this.data.sIndex + 1
      })
    } else {
      this.setData({
        sIndex: 0
      })
    }
    this.getDataList();

  },
  sureClick1: function () {
    //暂停招聘
    if (this.data.workInfo.status != 10) {
      var that = this;
      http.ztfactoryJobId(this.data.workInfo.id,
        function (res) {
          wx.hideLoading()
          console.log("-----暂停成功---", res);
          if (res.success) {
            that.data.workInfo.status == 10;
            getApp().globalData.workInfo.status = 10;
            that.setData({
              show1: false,
              workInfo: that.data.workInfo,
            })
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })

    }
    //开启招聘
    else if (this.data.workInfo.status == 10) {
      var that = this;
      http.kqfactoryJobId(this.data.workInfo.id,
        function (res) {
          wx.hideLoading()
          console.log("-----开启招聘成功---", res);
          if (res.success) {
            that.data.workInfo.status == 2
            that.setData({
              show1: false,
              workInfo: that.data.workInfo,
            })
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })
    } else {
      wx.showToast({
        title: '已完成无法无需暂停招聘',
        icon: "none",
      })
    }


  },
  sureClick() {
    this.operation()
  },
  onclickZP: function () {
    this.setData({
      show1: true,
      sm: this.data.workInfo.status == 10 ? "是否确定要恢复招聘" : "是否确定要暂停招聘"
    })
  },
  onclickre: function () {
    if (this.data.sIndex == 0) {
      this.setData({
        sIndex: this.data.titlist.length - 1
      })
    } else {
      this.setData({
        sIndex: this.data.sIndex - 1
      })
    }
    this.getDataList();
  },
  onclickmobile: function (e) {
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  onclickJS2: function (e) {
    var arr = this.data.dataList
    var uid = arr.map(function (elem) {
      if (elem.checked) {
        return elem.id;
      }
    }).join(",")
    let status = e.currentTarget.dataset.status;
    if (uid && uid != "") {

      this.onlcickJS(uid)

    } else {
      wx.showToast({
        title: '请选择对应人员后进行操作',
        icon: "none",
      })
    }

  },
  onlcickly1: function (e) {
    let index = e.currentTarget.dataset.index;
    this.data.funcStatus = index;
    this.data.isPl = true;
    let item = e.currentTarget.dataset.item;
    this.data.checkId = item.id;
    this.setData({
      show1: true,
      sm: index == 1 ? '您将确认为该员工不录用' : '您将确认为该员工录用',
      btnText: index == 1 ? "不录用" : '录用'
    })
  },
  onlcickJS1: function (e) {
    let item = e.currentTarget.dataset.item;
    let status = e.currentTarget.dataset.status;
    this.data.isPl = true;
    let index = e.currentTarget.dataset.index;
    this.data.checkId = item.id;
    this.data.funcStatus = index;
    this.setData({
      show1: true,
      sm: index == 19 ? '您将确认为该员工不结算' : '您将确认为该员工结算',
      btnText: index == 19 ? "不结算" : '结算'
    })
  },
  onlcickLY: function (id) {
    //  1取消录用  2录用
    let uId = null;
    if (Array.isArray(id)) {
      if (id.length > this.data.workInfo.number) {
        wx.showToast({
          title: '人数大于可录取人数',
          icon: "none"
        })
        return;
      }
      if (id.length > 0) {
        uId = id.join(',');
      } else {
        wx.showToast({
          title: '请选中一条',
          icon: 'none'
        })
        return;
      }
    } else {
      uId = id;
    }
    // 参数 :临时工ID 多个用','分割      //9结算 10审核
    let copyworkinfo = JSON.parse(JSON.stringify(this.data.workInfo))
    if(copyworkinfo.postType==2){
      this.data.uId = uId
      this.jobemploy()
      return
    }

    copyworkinfo.startDate = this.data.workInfo.startTime.split(' ')[0];
    copyworkinfo.startTime = this.data.workInfo.startTime.split(' ')[1];
    copyworkinfo.leaveDate = this.data.workInfo.leaveTime.split(' ')[0];
    copyworkinfo.leaveTime = this.data.workInfo.leaveTime.split(' ')[1];
    copyworkinfo.number = uId.split(',').length;


    let workTime = 0;
    // if (copyworkinfo.postType == 2) {
    //   if(copyworkinfo.payType=='月'){
    //     workTime = new Date(copyworkinfo.leaveDate).getMonth()-new Date(copyworkinfo.startDate).getMonth();
    //   }
    //   if(copyworkinfo.payType=='天'){
    //     workTime = new Date(copyworkinfo.leaveDate).getMonth()-new Date(copyworkinfo.startDate).getMonth()+1;
    //   }
    //   if(copyworkinfo.payType=='小时'){
    //     workTime = new Date(copyworkinfo.leaveDate).getMonth()-new Date(copyworkinfo.startDate).getMonth();
    //   }
    // }
    if (copyworkinfo.postType == 1 && copyworkinfo.payType == '次') {
      workTime = 1
    }
    if (copyworkinfo.postType == 1 && copyworkinfo.payType == '时'||copyworkinfo.payType == '小时') {
      workTime = (copyworkinfo.leaveTime[0] + copyworkinfo.leaveTime[1]) - (copyworkinfo.startTime[0] + copyworkinfo.startTime[1]);
    }
    if (copyworkinfo.postType == 1 && copyworkinfo.payType == '日' ||copyworkinfo.payType == '天') {
      workTime = ((new Date(copyworkinfo.leaveDate).getTime() - new Date(copyworkinfo.startDate).getTime()) / 3600 /1000/ 24)*1+1
      // workTime = parseFloat(((new Date('2021-07-19 18:00:00').getTime() - new Date('2021-07-12 08:00:00').getTime()) / 3600 / 24/1000)+1)
    }
    let fy = 0;
    fy = workTime * copyworkinfo.basicSalary * copyworkinfo.number
    fy += (copyworkinfo.floatSalary) * copyworkinfo.number*workTime;
    if (copyworkinfo.isPlay == 2) {
      fy = copyworkinfo.floatSalary * copyworkinfo.number*workTime;
    }




    // let workTime = (copyworkinfo.payType == '天' ? ((new Date(copyworkinfo.leaveDate).getTime() - new Date(copyworkinfo.startDate).getTime()) / 3600000 / 24 + 1) : (copyworkinfo.leaveTime[0] + copyworkinfo.leaveTime[1]) - (copyworkinfo.startTime[0] + copyworkinfo.startTime[1]));
    // let fy = 0;
    // copyworkinfo.workTime = workTime;

    // fy = workTime * copyworkinfo.basicSalary * copyworkinfo.number
    // if (copyworkinfo.postType == 2) {
    //   fy += (copyworkinfo.floatSalary * copyworkinfo.number);
    //   if (copyworkinfo.isPlay == 2) {
    //     fy = copyworkinfo.floatSalary * copyworkinfo.number;
    //   }
    // } else if (copyworkinfo.postType == 1) {
    //   fy += workTime * copyworkinfo.floatSalary * copyworkinfo.number
    // }

    copyworkinfo.number = uId.split(',').length;
    if(this.data.funcStatus==1){
      this.data.uId = uId
      this.data.fy = fy
      this.jobemploy()
      return
    }
    this.setData({
      toast: true,
      fy: fy,
      copyworkinfo,
      workTime: workTime + copyworkinfo.payType,
      uId: uId
    })
    return
  },
  onclickCopy: function () {
    wx.navigateTo({
      url: '/pages/home/pages/company/company?type=2',
    })
  },
  onclickKQ: function (e) {
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pages/home/pages/calendar/calendar',
    })
  },
  onclickCheck: function () {
    wx.navigateTo({
      url: '/pages/home/pages/company/company?type=1',
    })
  },
  onlcickJS(uId, status) {
    // 参数 :临时工ID 多个用','分割
    //9结算 10审核
    if(this.data.workInfo.postType==2){
      wx.showToast({
        title: '全职结算需在平台处理',
        icon:"none"
      })
      return false;
    }
    var that = this;
    if (Array.isArray(uId)) {
      if (uId.length > 0) {
        uId = uId.join(',');
      } else {
        wx.showToast({
          title: '请选中一条',
          icon: 'none'
        })
        return;
      }
    } else {
      uId = uId;
    }
    var str = uId + "/" + this.data.funcStatus
    http.closeAccount(str,
      function (res) {
        wx.hideLoading()
        console.log("-----岗位人员信息---", res);
        if (res.success) {
          that.resetArgs();
          wx.showToast({
            title: '操作成功'
          })
          wx.nextTick(() => {
            that.getDataList();
            // 结算通知员工端
            try {
              debugger
              if (that.data.funcStatus == 9) {
                http.subMsgforCloseAccount(uId, () => { }, () => { })
              }
            } catch (error) {
              console.log(error)
            }
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })


  },
  onChange: function (e) {
    let index = e.currentTarget.dataset.index;
    this.data.dataList[index].checked = !this.data.dataList[index].checked
    this.setData({
      dataList: this.data.dataList,
    })
  },
  onChange1: function (e) {
    let _this = this;
    var arr = this.data.dataList;
    arr.forEach(element => {
      if (element.status == 1) {
        element.checked = e.detail;
      }
    });
    this.setData({
      checked1: !this.data.checked1,
      dataList: arr,
    })
  },
  onChange2: function (e) {
    let _this = this;
    var arr = this.data.dataList;
    arr.forEach(element => {
      if (element.status == 4) {
        element.checked = e.detail;
      }
    });
    this.setData({
      checked1: !this.data.checked1,
      dataList: arr,
    })
  },
  batchAll(event) {
    let isOk = false;
    this.data.dataList.map(item => {
      item.checked && (isOk = true)
    })

    if (!isOk) {
      wx.showToast({
        title: '请选择一条',
        icon: "none"
      })
      return
    }
    this.setData({
      show1: true
    })
    let key = event.currentTarget.dataset.key;
    let btnText = "";
    let sm = "";
    switch (key) {
      case '1':
        sm = '您将确认为该员工不录用';
        btnText = "不录用";
        break;
      case '2':
        sm = '您将确认为该员工录用';
        btnText = "录用";
        break;
      case '19':
        sm = '您将确认为该员工不结算';
        btnText = "不结算";
        break;
      case '9':
        sm = '您将确认为该员工结算';
        btnText = "结算";
        break;
    }
    this.setData({
      btnText,
      funcStatus: key,
      sm,
      isPl: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // http.subMsgforCloseAccount('3', () => {}, () => {})
    // http.closeAccount('380/9',()=>{},()=>{})
    wx.setNavigationBarTitle({
      title: getApp().globalData.workInfo.name,
    })
    wx.getSystemInfo({
      success: (result) => {
        console.log("----", result);
        var rpx = result.windowHeight * 750 / result.windowWidth - 288;
        this.setData({
          sh: rpx
        })
      },
    })
    this.setData({
      workInfo: getApp().globalData.workInfo
    })
    this.getDataList();
  },
  getDataList: function (st) {
    var that = this;
    if (this.data.loading) return false;
    if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多信息了',
        icon: 'none'
      })
      return false;
    };
    this.data.loading = true;
    wx.showLoading()
    var data = {
      factoryJobId: this.data.workInfo.id,
      status: this.data.tabActive == 1 ? '1,3' : this.data.tabActive,
      pageNo: this.data.pageNo,
      pageSize: this.data.pageSize
    }
    http.applicantInPostId(data,
      (res) => {
        console.log("-----岗位人员信息---", res);
        wx.hideLoading()
        this.data.loading = false;
        if (res.success) {
          this.getCount(data)
          let dataList = res.data.records;
          dataList.forEach(element => {
            element.checked = false;
          });
          if (dataList.length == 0) {
            this.data.hasMore = false;
            return false;
          }
          this.setData({
            dataList: [...this.data.dataList, ...dataList],
            pageNo: this.data.pageNo + 1
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  tabChange(event) {
    let title = event.detail.title;
    this.setData({
      pageNo: 1,
      total: 0,
      dataList: [],
      loading: false,
      hasMore: true,
      tabActive: event.detail.name
    })
    wx.nextTick(() => {
      this.getDataList()
    })
  },
  operation() {
    let key = this.data.funcStatus;
    let isPl = this.data.isPl;
    let arr = [];
    this.data.dataList.map(item => {
      if (item.checked) {
        arr.push(item.id)
      }
    })

    if (isPl) {
      if (key == '1' || key == '2') {
        this.onlcickLY(this.data.checkId);
      } else if (key == '19' || key == '9') {
        this.onlcickJS(this.data.checkId)
      }
    } else {
      if (key == '1' || key == '2') {
        this.onlcickLY(arr);
      } else if (key == '19' || key == '9') {
        this.onlcickJS(arr)
      }
    }
    wx.nextTick(() => {
      this.setData({
        show1: false
      })
    })
  },
  resetArgs() {
    this.setData({
      pageNo: 1,
      show1: false,
      dataList: [],
      loading: false,
      hasMore: true,
      btnText: '',
      sm: "",
      isPl: false,
      checkId: '',
      checked1: false,
      checked2: false,
    })
  },
  getCount() {
    if (this.data.tabActive != 1) {
      return false;
    }
    var data = {
      factoryJobId: this.data.workInfo.id,
      status: this.data.tabActive == 1 ? '1,3' : this.data.tabActive,
      pageNo: this.data.pageNo,
      pageSize: this.data.pageSize
    }
    let _this = this;
    http.statisticsByUserStatus(data, res => {
      if (res.success) {
        let count = {
          sx: 0,
          ly: 0
        }
        res.data.map(item => {
          let key = item.status
          switch (key) {
            case 3:
              count.ly = item.count;
              break;
          }
        })
        this.setData({
          count
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: "none"
        })
      }
    }, err => { })
  },
  createWxPay() {
    let _this = this;
    wx.showLoading()
    //  不付款直接录用
    // _this.jobemploy();
    // return 
    http.createOrder(`${this.data.workInfo.id}/${this.data.fy}`, res => {
      wx.requestPayment({
        nonceStr: res.nonceStr,
        package: res.package,
        paySign: res.paySign,
        signType: res.signType,
        timeStamp: res.timeStamp,
        success(res) {
          _this.jobemploy();
        },
        fail(err) {
          wx.showToast({
            title: '支付失败',
            icon: 'none'
          })
        }
      })
    }, err => {
      wx.showToast({
        title: err,
        icon: "none"
      })
    })
  },
  hidetoast() {
    this.setData({
      toast: false
    })
  },
  onclickSure() {
    console.log(666)
  },
  jobemploy() {
    var that = this;
    var str = this.data.uId + "/" + this.data.funcStatus
    debugger
    http.updateHireStatus(str,
      function (res) {
        wx.hideLoading()
        console.log("-----岗位人员信息---", res);
        if (res.success) {
          that.resetArgs();

          wx.showToast({
            title: that.data.funcStatus==1?'操作成功':res.message,
            icon: "none",
            success() {
              var timer = setTimeout(() => {
                that.getDataList();
                that.data.uId = "";
                that.setData({
                  toast: false,
                  show1: false
                })
                clearTimeout(timer);
              }, 1000)
            }
          })
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })
  }
})
